//
//  RegistrationConfirmController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/4/20.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class RegistrationConfirmController: BaseViewController {
    
    var scheduleViewModel: DoctorScheduleViewModel
    let doctorViewModel: DoctorDetailViewModel
    let registrationListViewModel: CloudReserveDateListViewModel
    var familyRowViewModel: FamilyRowViewModel?
    var isAgree = false
    
    init(with doctorVm: DoctorDetailViewModel, scheduleVm: DoctorScheduleViewModel, registrationListVm: CloudReserveDateListViewModel) {
        scheduleViewModel = scheduleVm
        doctorViewModel = doctorVm
        registrationListViewModel = registrationListVm
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "预约"
        setUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setNav(type: 0)
        setBack()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        setNav(type: 1)
    }
    
    func setBack() {
//        let backItem = UIBarButtonItem(imageName: "back_arrow_white", target: self, action: #selector(back))
//        if UIDevice.avaiableSystem < 11 {
//            let spaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
//            spaceItem.width = -10.0
//            navigationItem.leftBarButtonItems = [spaceItem, backItem]
//        } else {
//            navigationItem.leftBarButtonItem = backItem
//        }
    }
    
    func setNav(type: Int) {
        // 0:appear 1:disappear
//        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.medium(18),
//                                                                   NSAttributedString.Key.foregroundColor: type == 0 ? UIColor.white : UIColor.textDark]
//
//        if type == 0 {
//            setNavClear()
//        }  else {
//            setNavWhite()
//        }
    }
    
    func setUI() {
        tableView.tableFooterView = UIView()
        tableView.register(MyAdvisoryOrderFinishHeaderCell.nibForCell(),
                           forCellReuseIdentifier: MyAdvisoryOrderFinishHeaderCell.reuseIdentifier())
        tableView.register(MyAdvisoryOrderFinishDiagnoseCell.nibForCell(),
                           forCellReuseIdentifier: MyAdvisoryOrderFinishDiagnoseCell.reuseIdentifier())
        tableView.register(RegistrationConfirmPatientCell.nibForCell(),
                           forCellReuseIdentifier: RegistrationConfirmPatientCell.reuseIdentifier())
        tableView.register(RegistrationConfirmAgreeCell.nibForCell(),
                           forCellReuseIdentifier: RegistrationConfirmAgreeCell.reuseIdentifier())
    
    }
    
    @objc func back() {
        navigationController?.popViewController(animated: true)
    }
    
    func pushToRegistrationDetail(registrationId: String) {
        let vc = RegistrationDetailController(registrationId: registrationId)
        removeCurrentVcWhenPush(vc)
    }
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var confirmBtn: UIButton! {
        didSet {
            confirmBtn.layer.cornerRadius = confirmBtn.height / 2.0
            confirmBtn.layer.masksToBounds = true
        }
    }
    
    @IBAction func confirmBtnAcion(_ sender: Any) {
        submitRegistration()
    }
}

extension RegistrationConfirmController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 1
        case 1: return 1
        case 2: return 1
        case 3: return 1
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: MyAdvisoryOrderFinishHeaderCell.reuseIdentifier(), for: indexPath) as! MyAdvisoryOrderFinishHeaderCell
            cell.updateDataForRegistration(vm: doctorViewModel)
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: MyAdvisoryOrderFinishDiagnoseCell.reuseIdentifier(), for: indexPath) as! MyAdvisoryOrderFinishDiagnoseCell
            cell.updateForRegistration(doctorVm: doctorViewModel, scheduleVm: scheduleViewModel, registrationListVm: registrationListViewModel)
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: RegistrationConfirmPatientCell.reuseIdentifier(), for: indexPath) as! RegistrationConfirmPatientCell
            if let vm = familyRowViewModel {
                cell.updateData(vm: vm)
            }
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: RegistrationConfirmAgreeCell.reuseIdentifier(), for: indexPath) as! RegistrationConfirmAgreeCell
            cell.delegate = self
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return 116
        case 1: return UITableView.automaticDimension
        case 2: return 81
        case 3: return 44
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 2 else { return }
        pushFamilyVc()
    }
}

extension RegistrationConfirmController: FamilyViewControllerDelegate, RegistrationConfirmAgreeCellDelegate {
    func familyVc(_ vc: FamilyViewController, didSelected vm: FamilyRowViewModel) {
        familyRowViewModel = vm
        tableView.reloadRows(at: [IndexPath(row: 0, section: 2)], with: .none)
    }
    
    func registrationConfirmAgreeCellAgreeBtnAction(sender: UIButton) {
        isAgree = sender.isSelected
    }
}

extension RegistrationConfirmController {
    private func pushFamilyVc() {
        let familyVc = FamilyViewController()
        familyVc.delegate = self
        navigationController?.pushViewController(familyVc, animated: true)
    }
}

extension RegistrationConfirmController {
    func submitRegistration() {
        guard let familyVm = familyRowViewModel else {
            HUDTool.show(message: "请选择就诊人")
            return
        }
        
        guard isAgree else {
            HUDTool.show(message: "请阅读并同意挂号须知")
            return
        }
        
        confirmBtn.isEnabled = false
        HUDTool.showActivity()
        PublishViewModel.reserveDoctorNumber(numberId: registrationListViewModel.scheduleId,
                                             patientId: familyVm.patientId,
                                             doctorId: doctorViewModel.doctorId,
                                             departmentId: doctorViewModel.departmentId,
                                             businessType: 3,
                                             regDocId: familyVm.patientId)
        { (registrationId, msg, code) in
            HUDTool.hideActivity()
            self.confirmBtn.isEnabled = true
            switch code {
            case .failure:
//                HUDTool.hideActivity()
                HUDTool.showError(message: msg)
            case .success:
//                self.insertRegistration(scheduleId: self.registrationListViewModel.scheduleId, patientId: familyVm.patientId, patientName: familyVm.name)
                if let regId = registrationId?.scheduleId {
                    self.pushToRegistrationDetail(registrationId: regId)
                }
            }
        }
    }
    
    func insertRegistration(scheduleId: String, patientId: String, patientName: String) {
        RegistrationViewModel.insertRegistration(scheduleId: scheduleId,
                                                 patientId: patientId)
        { (registrationId, msg, code) in
            switch code {
            case .failure:
                self.cancelRegistration(scheduleId: scheduleId, patientName: patientName)
            case .success:
                HUDTool.hideActivity()
                if let regId = registrationId {
                    self.pushToRegistrationDetail(registrationId: regId)
                }
            }
        }
    }
    
    func cancelRegistration(scheduleId: String, patientName: String) {
        RegistrationViewModel.deleteRegistration(scheduleId: scheduleId,
                                                 patientName: patientName)
        { (msg, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: msg)
            case .success:
                HUDTool.show(message: "预约失败,请重试!")
            }
        }
    }
}

